/*********************************************************************************
  *Copyright (c)    2021   xldeng
  *FileName:        51.cpp.c
  *Author:          xldeng
  *Version:         1.0
  *Date:            2021/2/8 14:32
  *Description:     
  *Others:          
  *Function List:   
     1.…………
  *History:  
     1.Date:
       Author:
       Modification:
**********************************************************************************/
/*
 * n 皇后问题
 */
#include <string>
#include <vector>

using namespace std;

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        ans.clear();
        vector<string> board(n, string(n, '.'));
        traceback(board, 0);
        return ans;
    }

private:
    vector<vector<string>> ans;

    void traceback(vector<string> &board, int row) {
        if (row == board.size()) {
            ans.emplace_back(board);
            return;
        }
        int n = board[row].size();
        for (int col = 0; col < n; ++col) {
            if (!is_valid(board, row, col))
                continue;
            board[row][col] = 'Q';
            traceback(board, row + 1);
            board[row][col] = '.';
        }
    }

    bool is_valid(vector<string> &board, int row, int col) {
        int n = board.size();
        for (int i = 0; i < row; ++i) {
            if (board[i][col] == 'Q')
                return false;
        }
        for (int i = row - 1, j = col + 1; i >= 0 && j < n; --i, ++j) {
            if (board[i][j] == 'Q')
                return false;
        }
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j) {
            if (board[i][j] == 'Q')
                return false;
        }
        return true;
    }
};